package com.laboratory.websocketlearning.config;

import com.laboratory.websocketlearning.handler.ChatHandler;
import com.laboratory.websocketlearning.interceptor.AuthHandshakeInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketConfigurer {

    private final ChatHandler chatHandler;

    private final AuthHandshakeInterceptor authHandshakeInterceptor;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        /**
         * 作用：把名为 chatHandler 的处理器绑定到路径 /ws/chat。
         * 效果：浏览器或客户端可通过 ws://<host>/ws/chat（或 wss://...）发起握手并建立 WebSocket 连接。
         * 补充：chatHandler 通常是你自定义的类（例如继承 TextWebSocketHandler），负责 afterConnectionEstablished、handleTextMessage、afterConnectionClosed 等事件的业务逻辑。
         */
        registry.addHandler(chatHandler, "/ws/chat")
                .addInterceptors(authHandshakeInterceptor)
                .setAllowedOrigins("*");
    }

}
